﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;
using System.IO;

namespace OutlookContactCategoriesCorrection
{
    public partial class frmMain : Form
    {
        Outlook.Application olApp = new Outlook.Application();
        Outlook.MAPIFolder folBackup;
        Outlook.MAPIFolder folCurrent;
        List<GroupBox> groups = new List<GroupBox>();

        public frmMain()
        {
            InitializeComponent();
            // add the groups to the list
            groups.Add(grpStep0);
            groups.Add(grpStep1);
            groups.Add(grpStep2);
            groups.Add(grpStep3);
        }

        private void btnBrowseOriginal_Click(object sender, EventArgs e)
        {
            folBackup = olApp.Session.PickFolder();
            if (folBackup != null && folBackup.DefaultItemType == Outlook.OlItemType.olContactItem)
            {
                txtBackupPath.Text = folBackup.FolderPath;
                btnNext.Enabled = true;
            }
        }

        private void btnBrowseCurrent_Click(object sender, EventArgs e)
        {
            folCurrent = olApp.Session.PickFolder();
            if (folCurrent != null && folCurrent.DefaultItemType == Outlook.OlItemType.olContactItem)
            {
                txtCurrentPath.Text = folCurrent.FolderPath;
                btnNext.Enabled = true;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show("Are you sure you want to exit the wizard?", 
                                                  "Exit Wizard", MessageBoxButtons.YesNoCancel);
            if (result == System.Windows.Forms.DialogResult.Yes)
            {
                // Exit the application
                Application.Exit();
            }
        }

        int currentStep = 0;
        private void btnNext_Click(object sender, EventArgs e)
        {
            if (currentStep == groups.Count - 1)
            {
                finish();
            }
            else
            {
                changeStep(1);
                if (currentStep == groups.Count - 1)
                {
                    btnBack.Enabled = false;
                    btnNext.Text = "Correct";
                    btnNext.Enabled = true;
                }
            }
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            changeStep(-1);
        }

        private void changeStep(int increment)
        {
            // hide all the groups
            foreach (GroupBox g in groups)
                g.Visible = false;

            currentStep+=increment;
            groups[currentStep].Visible = true;
            groups[currentStep].Top = grpStep0.Top;
            groups[currentStep].Left = grpStep0.Left;
            groups[currentStep].Height = grpStep0.Height;
            groups[currentStep].Width = grpStep0.Width;
            btnNext.Enabled = false;
        }

        private void finish()
        {
            btnClose.Enabled = false;
            btnBack.Enabled = false;
            btnNext.Enabled = false;

            pbStatus.Maximum = folBackup.Items.Count + folCurrent.Items.Count;

            // get a list of all the contacts and theior categories from the backup copy
            lstLog.Items.Add(DateTime.Now + " [STARTING]");
            Dictionary<string, string> contactList = new Dictionary<string, string>();
            lstLog.Items.Add(DateTime.Now + " - User selected 'backup' folder: " + folBackup.FolderPath);
            lstLog.Items.Add(DateTime.Now + " - Indexing backup contacts.");
            lblStatus.Text = "Indexing backup contacts...";
            for (int i = 1; i <= folBackup.Items.Count; i++)
            {
                try
                {
                    pbStatus.Increment(1);
                    Outlook.ContactItem item = folBackup.Items[i];
                    contactList.Add(HashContact(item), item.Categories);
                    lstLog.Items.Add(DateTime.Now + " - Adding: " + item.FullName + " = " + item.Categories);
                }
                catch (Exception ex)
                {
                    lstLog.Items.Add(DateTime.Now + " - ERROR: " + ex.ToString().Replace("\n", "|").Replace("\r", "|"));
                }
            }

            // next, loop through the contacts and correct categories of contacts
            lblStatus.Text = "Indexing current contacts...";
            lstLog.Items.Add(DateTime.Now + " - User selected 'current' folder: " + folCurrent.FolderPath);
            lstLog.Items.Add(DateTime.Now + " - Indexing current contacts.");
            for (int i = 1; i <= folCurrent.Items.Count; i++)
            {
                try
                {
                    pbStatus.Increment(1);
                    Outlook.ContactItem item = folCurrent.Items[i];
                    string hash = HashContact(item);
                    // do we have the category for this contact
                    if (contactList.ContainsKey(hash))
                    {
                        // correct the category for this contact
                        item.Categories = contactList[hash];
                        lstLog.Items.Add(DateTime.Now + " - Correcting: " + item.FullName + " = " + item.Categories);
                    }
                }
                catch (Exception ex)
                {
                    lstLog.Items.Add(DateTime.Now + " - ERROR: " + ex.ToString().Replace("\n", "|").Replace("\r", "|"));
                }
            }
            // done
            lstLog.Items.Add(DateTime.Now + " [COMPLETE]");

            // save to log file
            string path = Path.GetTempPath() + "OutlookContactCategoryCorrection.log";
            StreamWriter sw = new StreamWriter(path, false);
            foreach (string itm in lstLog.Items)
                sw.WriteLine(itm);
            sw.Close();

            // exit the application
            MessageBox.Show("Complete! Log is saved to the temp folder. \n\n" + path, 
                            "Compelte", MessageBoxButtons.OK, MessageBoxIcon.Information);
            btnClose.Enabled = true;
        }

        private string HashContact(Outlook.ContactItem item)
        {
            return item.FullName + "-" + item.CompanyName + "-" + item.Email1Address;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            //562, 352
            this.Width = 562;
            this.Height = 352;
        }
    }
}